<?php
/*
Plugin Name: Business Directory
Plugin URI: http://localreport.org/
Description: Add a simple business directory plugin that allows you to list businesses on your site, with custom post types.
Version: 0.1
Author: Jeremy Rue
Author URI: http://localreport.org/
License: GPL2

Copyright 2011  JEREMY RUE  (email : jrue@localreport.org)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as 
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

class BusinessDirectoryListing{

	function BusinessDirectoryListing()
	{
    
		// Creates business listing post type labels
		$business_labels = array(
			'name' => _x('Business Listings', 'Business listing custom post type general plural name'),
			'singular_name' => _x('Business Listing', 'Business listing custom post type singular name'),
			'add_new' => _x('Add New', 'Business Listing'),
			'add_new_item' => __('Add New Business Listing'),
			'edit_item' => __('Edit Business Listings'),
			'new_item' => __('New Business Listing'),
			'view_item' => __('View Business Listings'),
			'search_items' => __('Search Business Listings'),
			'not_found' =>  __('No Business Listings found'),
			'not_found_in_trash' => __('No Business Listings found in Trash'), 
			'parent_item_colon' => '',
			'menu_name' => __('Business Listings')
		);
		
		//Business listings only use title, editor, thumbnail and author. 
		$business_support = array(
			'title',
			'editor',
			'thumbnail',
			'author',
		);
		
		//put it all together
		$business_label = array(
			'labels' => $business_labels,
			'public' => true,
			'show_ui' => true,
			'capability_type' => 'post',
			'hierarchical' => false,
			'rewrite' => array('slug' => 'businesslistings', 'with_front' => TRUE),
			'query_var' => true,
			'supports' => $business_support
		);
		
		//register this custom post type in WP
		register_post_type('business_listings', $business_label);
		
		//Some JS and CSS for the date picker form only in the admin
		add_action('admin_print_scripts', array(&$this, 'add_business_listing_admin_scripts') );
		add_action('admin_print_styles', array(&$this, 'add_business_listing_admin_styles') );
	
		//Build the form box for business listing custom posts, and save meta data
		add_action('admin_init', array(&$this, 'admin_init') );
		add_action('save_post', array(&$this, 'save_business_listing_data') );
		
		//messages after you submit the form
		add_filter('post_updated_messages', array(&$this, 'business_listing_updated_messages') );
		
		//add settings menu for Googles re-captcha code
		if ( is_admin() ){
			//add_action('admin_menu', array(&$this, 'classifieds_menu_page') );
			//add_action('admin_init', array(&$this, 'classifieds_settings') );
		}
	}
	
	function add_business_listing_admin_scripts()
	{
		//For the date picker to show up when clicking inside date field in admin
		$plugin_dir = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__), "", plugin_basename(__FILE__));
		//wp_enqueue_script('jquery');
		//wp_enqueue_script('jquery_date_picker', $plugin_dir .'js/jquery-ui-1.8.11.custom.min.js', array('jquery'), '1.2.1');
	}
	
	function add_business_listing_admin_styles()
	{
		//date picker styles
		$plugin_dir = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__), "", plugin_basename(__FILE__));
		//wp_enqueue_style('jquery_date_picker_css', $plugin_dir .'js/css/smoothness/jquery-ui-1.8.11.custom.css');
	}
	
	function admin_init() 
	{
		// Custom meta boxes for expiration, price and location
		add_meta_box('businesslisting-meta', 'Business Listing Options', array(&$this, 'meta_options'), 'business_listings', 'normal', 'high');
	}

	// Admin post meta contents
	function meta_options()
	{
		global $post;
		global $geotag_options; 
	  
	  $key = $geotag_options["gmap_api_key"];
    $base_url = "http://maps.google.com/maps/geo?output=xml" . "&key=" . $key;
		
		//security measure to make sure this form submission comes only from this page
		wp_nonce_field( plugin_basename( __FILE__ ), 'businesslisting_noncename' );
		
		//pre-populate forms with saved data
		$custom = get_post_custom($post->ID);
		$business_website = $custom['_business-website'][0] ? $custom['_business-website'][0] : '';
		$business_ad = $custom['_business-ad'][0] ? $custom['_business-ad'][0] : '';
		$business_location = $custom['_business-location'][0] ? $custom['_business-location'][0] : '';
		$brief_description = $custom['_brief-description'][0] ? $custom['_brief-description'][0] : '';
		$business_latitude = $custom['_business-latitude'][0] ? $custom['_business-latitude'][0] : '';
		$business_longitude = $custom['_business-longitude'][0] ? $custom['_business-longitude'][0] : '';
		
		//HTML for meta forms for expiration, price and location
		_e('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>');
		
		echo "
		  <script type=\"text/javascript\">
		    function geocode_address(address){
          var geocoder = new google.maps.Geocoder();
          geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                document.getElementById('business-latitude').value = latitude;
                document.getElementById('business-longitude').value = longitude;
            } else {
                  alert(\"Error Geocoding. Reason:\" + String(status));
            };
          });
        }
      </script>";
		
		_e("<p><label for=\"brief-description\">Brief description (Don't include business name or it will be redundant):</label><br />\n");
		_e("<input name=\"brief-description\" id=\"brief-description\" type=\"text\" value=\"$brief_description\" style=\"width:50%\" /></p>\n");
		_e("<p><label for=\"business-website\">Business Website:</label><br />\n");
		_e("<input name=\"business-website\" id=\"business-website\" type=\"text\" value=\"$business_website\" style=\"width:50%\" /></p>\n");
		_e("<p><label for=\"business-ad\">Custom Ad Embed Code:</label><br />\n");
		_e("<input name=\"business-ad\" id=\"business-ad\" type=\"text\" value=\"". esc_attr($business_ad) ."\" style=\"width:50%\" /></p>\n");
		_e("<p><label for=\"business-location\">Complete business address with city and state</label><br />\n");
		_e("<input name=\"business-location\" id=\"business-location\" type=\"text\" value=\"$business_location\" style=\"width:50%\" />&nbsp;");
		_e("<input name=\"geocode\" id=\"geocode\" type=\"button\" value=\"Geocode\" onclick=\"geocode_address(document.getElementById('business-location').value)\" /></p>\n");
		_e("<p><label for=\"business-latitude\">Latitude:</label><br />\n");
		_e("<input name=\"business-latitude\" id=\"business-latitude\" type=\"text\" value=\"$business_latitude\" style=\"width:50%\" /></p>\n");
		_e("<p><label for=\"business-longitude\">Longitude:</label><br />\n");
		_e("<input name=\"business-longitude\" id=\"business-longitude\" type=\"text\" value=\"$business_longitude\" style=\"width:50%\" /></p>\n");
		_e("<p style=\"font-size:.9em\">Note: Make sure to update or save this post after geocoding or coordinates will be lost.</p>");
	}

	function save_business_listing_data($post_id) 
	{	
		// verify this came from the our screen and with proper authorization.
		if ( !wp_verify_nonce( $_POST['businesslisting_noncename'], plugin_basename( __FILE__ ) ))
			return $post_id;

		// verify if this is an auto save routine. If it is, our form has not been submitted, so we dont want to do anything
		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
			return $post_id;

		// Check permissions
		if ( !current_user_can( 'publish_pages', $post_id ) )
			return $post_id;

		// OK, we're authenticated: we need to find and save the data	
		$post = get_post($post_id);
		if ($post->post_type == 'business_listings') { 
		  update_post_meta($post_id, '_business-website', esc_attr($_POST['business-website']) );
		  update_post_meta($post_id, '_business-ad', $_POST['business-ad'] );
		  update_post_meta($post_id, '_business-location', esc_attr($_POST['business-location']) );
			update_post_meta($post_id, '_brief-description', esc_attr($_POST['brief-description']) );
			update_post_meta($post_id, '_business-latitude', esc_attr($_POST['business-latitude']) );
			update_post_meta($post_id, '_business-longitude', esc_attr($_POST['business-longitude']) );
		}
		return $post_id;
	}
	
	function business_listing_updated_messages( $messages ) 
	{
		global $post, $post_ID;
		$messages['business_listings'] = array(
			0 => '', // Unused. Messages start at index 1.
			1 => sprintf( __('Business listing updated. <a href="%s">View Business Listing.</a>'), esc_url( get_permalink($post_ID) ) ),
			2 => __('Custom field updated.'),
			3 => __('Custom field deleted.'),
			4 => __('Business Listing updated.'),
			/* translators: %s: date and time of the revision */
			5 => isset($_GET['revision']) ? sprintf( __('Business listing restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
			6 => sprintf( __('Business listing published. <a href="%s">View business listing</a>'), esc_url( get_permalink($post_ID) ) ),
			7 => __('Business listing saved.'),
			8 => sprintf( __('Business listing submitted. <a target="_blank" href="%s">Preview business listing</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
			9 => sprintf( __('Business listing scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview business listing</a>'),
			// translators: Publish box date format, see http://php.net/date
			date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
			10 => sprintf( __('Business listing draft updated. <a target="_blank" href="%s">Preview business listing</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
		);
		return $messages;
	}
	
}


add_action('init', 'BusinessDirectoryListingInit');

function BusinessDirectoryListingInit(){ 
	global $businessDirectory; 
	$businessDirectory = new BusinessDirectoryListing();
}

function businessDirectory_rewrite_flush() {
  BusinessDirectoryListingInit();
  flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'businessDirectory_rewrite_flush');
?>